package edu.gzy.rpsm_property.controller;

import edu.gzy.rpsm_property.mapper.PayMapper;
import edu.gzy.rpsm_property.mapper.RoomMapper;
import edu.gzy.rpsm_property.pojo.Amount;
import edu.gzy.rpsm_property.pojo.PageResult;
import edu.gzy.rpsm_property.pojo.ResponsePojo;
import edu.gzy.rpsm_property.pojo.vo.PayInfo;
import edu.gzy.rpsm_property.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

@RestController
@RequestMapping("/pay")
@Api(tags = "支付信息API")
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private PayMapper payMapper;

    @GetMapping("/payInfos")
    @ApiOperation("支付信息分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页数", dataTypeClass = Integer.class, defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页条数", dataTypeClass = Integer.class, defaultValue = "10"),
            @ApiImplicitParam(name = "start", value = "开始日期"),
            @ApiImplicitParam(name = "end", value = "结束日期"),
            @ApiImplicitParam(name = "username", value = "用户姓名"),
            @ApiImplicitParam(name = "idCard", value = "身份证"),
            @ApiImplicitParam(name = "floorId", value = "楼层ID"),
            @ApiImplicitParam(name = "buildingId", value = "建筑ID")
    })
    public ResponsePojo<PageResult<PayInfo>> getPaysInfo(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            LocalDate start,
            LocalDate end,
            String username,
            String idCard,
            Integer floorId,
            Integer buildingId
    ) {
        // 如果 start 和 end 都为空，默认为今天
        if (start == null && end == null) {
            end = LocalDate.now();
        }
        // 调用 payService 方法获取分页结果
        PageResult<PayInfo> page = payService.pageOfPayInfo(current, size, start, end, username, idCard, floorId, buildingId);
        return ResponsePojo.success(page);
    }

    @PostMapping("/insertUnpaid")
    @ApiOperation(value = "新增未支付费用信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "amount_roomid", value = "房间ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "amount", value = "费用金额", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "amount_date", value = "费用日期", dataType = "String", example = "2024-11-14"),
            @ApiImplicitParam(name = "amount_type", value = "费用类型", required = true, dataType = "Byte")
    })
    public ResponsePojo<Integer> insertUnpaid(
            @RequestParam Integer amount_roomid,  // 获取房间ID
            @RequestParam Integer amount,        // 获取费用金额
            @RequestParam(required = false) String amount_date, // 获取费用日期
            @RequestParam Byte amount_type       // 获取费用类型
    ) {
        // 校验房间ID不能为空
        if (amount_roomid == null) {
            return ResponsePojo.fail(null, "房间ID不能为空");
        }

        // 设置默认日期为当前时间（如果没有传递日期）
        if (amount_date == null || amount_date.isEmpty()) {
            amount_date = LocalDate.now().toString();  // 使用当前时间
        }
        // 验证支付类型是否为1（水费）、2（电费）或3（物业费）
        if (amount_type == null || !(amount_type == 1 || amount_type == 2 || amount_type == 3)) {
            return ResponsePojo.fail(null, "支付类型必须为1（水费）、2（电费）或3（物业费）");
        }

        // 创建 Amount 对象并赋值
        Amount amountEntity = new Amount();
        amountEntity.setAmount_roomid(amount_roomid);
        amountEntity.setAmount(amount);
        amountEntity.setAmount_date(LocalDate.parse(amount_date));
        amountEntity.setAmount_type(amount_type);
        amountEntity.setIsPaid(2);  // 默认为未支付

        Integer result = null;
        try {
            // 调用服务层插入数据
            result = payService.insertUnpaid(amountEntity);
            return ResponsePojo.success(result);
        } catch (DuplicateKeyException e) {
            // 处理重复键异常
            return ResponsePojo.fail(result, "新增未支付费用信息失败：重复的房间ID或费用记录");
        } catch (Exception e) {
            // 处理其他异常
            return ResponsePojo.fail(result, "新增未支付费用信息失败");
        }
    }

    @PostMapping("/pay")
    @ApiOperation(value = "欠费支付，更新欠费", notes = "记录支付信息并更新欠费状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "paymentAmount", value = "支付金额", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "payType", value = "费用类型（1:水费, 2:电费, 3:物业费）", required = true, dataType = "Integer")
    })
    public ResponsePojo<Integer> payForRoom(
            @RequestParam Integer roomId,
            @RequestParam Integer paymentAmount,
            @RequestParam Integer payType
    ) {
        try {
            //进行支付和欠费状态更新
            payService.handlePayment(roomId, paymentAmount, payType);

            return ResponsePojo.success(1);
        } catch (Exception e) {
            return ResponsePojo.fail(2, "支付失败: " + e.getMessage());
        }
    }
}
